﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QThread>
#include <QVBoxLayout>
#include <QDir>
#include <QFileDialog>
#include "appsettings.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    log = new logWidget();
    crc32Tool = new crc32();
    connect(ui->listWidget, &QListWidget::currentRowChanged, ui->stackedWidget, &QStackedWidget::setCurrentIndex);
    ui->listWidget->setStyleSheet("QListWidget { background-color: #f0f0f0; }"
                                  "QListWidget::item { padding: 10px; }"
                                  "QListWidget::item:selected { background-color: #c0c0c0; }");

    clientThread = new QThread(this);
    tcpClient = new TcpClient();
    tcpClient->moveToThread(clientThread);

    connect(tcpClient, &TcpClient::messageReceived, this, &MainWindow::onMessageReceived);
    connect(tcpClient, &TcpClient::connected, this, &MainWindow::onConnected);
    connect(tcpClient, &TcpClient::disconnected, this, &MainWindow::onDisconnected);

    // 启动线程
    clientThread->start();

    timerSend.setInterval(1000);
    timerSend.setSingleShot(true);
    connect(&timerSend,&QTimer::timeout,this,&MainWindow::timerSendTimeout);
}

MainWindow::~MainWindow()
{
    if(crc32Tool)
        crc32Tool->deleteLater();
    crc32Tool=nullptr;
    tcpClient->disconnectServer();
    clientThread->quit();
    clientThread->wait();
    delete tcpClient;
    if(log)
        log->deleteLater();
    log->deleteLater();
    delete ui;
}

void MainWindow::on_actionCRC32_triggered()
{
    if(crc32Tool)
        crc32Tool->show();
}

void MainWindow::on_pushButton_clicked()
{
    if(ui->pushButton->text()==tr("Connect"))
    {
        QString addr = ui->lineEdit_ip->text();
        QString port = ui->lineEdit_port->text();
        if(addr==""||port=="")
            return;
        bool flag=false;

        int _port = port.toUInt(&flag,10);
        if(flag==false)
            return;
        QMetaObject::invokeMethod(tcpClient, "connectToServer", Qt::QueuedConnection,Q_ARG(QString,addr),Q_ARG(int,_port));
    }
    else if(ui->pushButton->text()==tr("Disconnect"))
    {
        QMetaObject::invokeMethod(tcpClient, "disconnectServer", Qt::QueuedConnection);
        ui->pushButton->setText(tr("Connect"));
    }
}

void MainWindow::onMessageReceived(const QString &message)
{
    qDebug()<<__func__<<message;
}

void MainWindow::onConnected()
{
    qDebug()<<__func__<<"Connected to server.";
    log->setLog("Connected to server.");
    ui->pushButton->setText(tr("Disconnect"));
    timerSend.start();
}

void MainWindow::onDisconnected()
{
    qDebug()<<__func__<<"Disconnected from server.";
    log->setLog("Disconnected from server.");
}

void MainWindow::on_actionLOG_triggered()
{
    if(log->isHidden())
        log->show();
}


void MainWindow::on_actionimport_json_triggered()
{
    QString fileName="";
    QString path;
    path = appSettingsInstance->getSetting(JSONPATH).toString();
    if(path=="")
    {
        path = QDir::currentPath();
        fileName = QFileDialog::getOpenFileName(this,tr("Select json"),path,tr("Json (*.json)"));
    }
    else
    {
        fileName = QFileDialog::getOpenFileName(this,tr("Select json"),path,tr("Json (*.json)"));
    }
    appSettingsInstance->setSetting(JSONPATH,QFileInfo(fileName).absolutePath());
    if(fileName=="")
    {
        return;
    }
    QFile file(fileName);
    QTextStream stream;
    if(!file.open(QIODevice::ReadOnly))
        return;
    stream.setDevice(&file);
    QString content = stream.readAll();
    file.close();
    bool flag = jsonPrase::prase(content,jsondata);
    if(!flag)
    {
        log->setLog("prase json failed!");
        return;
    }
}

void MainWindow::timerSendTimeout()
{
    if(jsondata.cmdList.size()<=0)
        return;
    if(!tcpClient)
        return;
    if(timerSendIndex>=jsondata.cmdList.size())
        return;
    Item item = jsondata.cmdList.at(timerSendIndex);
    QString msg = "  key:"+item.key+ "  Name:"+item.name+"  action:"+item.action+"  cmd:"+item.cmd;
    QMetaObject::invokeMethod(tcpClient, "sendMessage", Qt::QueuedConnection,Q_ARG(QString,msg));
    timerSendIndex++;
    timerSend.start();
}
